package com.apinji.alipay.dao.daoimpl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.apinji.alipay.common.AlipayErrorCodeEnum;
import com.apinji.alipay.common.AlipayTradeStatusEnum;
import com.apinji.alipay.dao.AlipayConsumeDao;
import com.apinji.alipay.protocol.BizContentRequest;
import com.apinji.alipay.sdk.AlipaySdkConfig;
import com.apinji.common.domain.wrapper.Reply;
import com.apinji.common.plugin.Mutual;
import com.apinji.common.plugin.StrUtils;
import com.apinji.common.plugin.fastjson.JSONUtils;
import com.apinji.alipay.protocol.AlipayTradeQueryResponse;
import org.springframework.stereotype.Service;

@Service
public class AlipayConsumeDaoImpl implements AlipayConsumeDao {

    @Override
    public Reply alipayTradeQuery(String outOrderId, String queryId) {
        AlipaySdkConfig alipaySdkConfig = AlipaySdkConfig.getInstance();
        //
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipaySdkConfig.getGatewayUrl(),
                alipaySdkConfig.getAppId(),
                alipaySdkConfig.getMerchantPrivateKey(),
                "json",
                alipaySdkConfig.getCharset(),
                alipaySdkConfig.getAlipayPublicKey(),
                alipaySdkConfig.getSignType()
        );
        //
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //
        BizContentRequest request = new BizContentRequest();
        request.setOutOrderId(outOrderId);
        request.setQueryId(queryId);
        alipayRequest.setBizContent(JSONUtils.parseJsonStr(request));

        String result = "";
        try {
            //请求
            result = alipayClient.execute(alipayRequest).getBody();
            //
            if(StrUtils.isEmpty(result)) {
                return Mutual.serverError("支付宝返回为空");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Mutual.serverError(e);
        }
        //
        JSONObject jsonObject = JSONUtils.parseJsonObject(result);
        AlipayTradeQueryResponse alipayTradeQueryResponse = JSONUtils.toJavaObject(jsonObject.getJSONObject("alipay_trade_query_response"), AlipayTradeQueryResponse.class);
        //接口访问成功  &&   交易成功
        if(alipayTradeQueryResponse.getCode() == AlipayErrorCodeEnum.SUCCESS.getCode() &&
                alipayTradeQueryResponse.getTradeStatus().equals(AlipayTradeStatusEnum.TRADE_SUCCESS.getStatus())) {
            return Mutual.success(alipayTradeQueryResponse);
        }
        //
        return Mutual.serverError(alipayTradeQueryResponse);
    }
}
